<template>
  <view class="content">
    <TnDateTimePicker
      v-model="skipToDate"
      mode="date"
      :open="skipDatePickerShow"
      @confirm="confirmSkipToDate"
      @close="closeSkipDatePicker"
    />
    <view class="calendar-box">
      <view class="calendar-header">
        <view class="arrow" @click="changeCalendar('prev')">
          <image src="/static/icons/larrow.png" mode="aspectFit" />
        </view>
        <view>
          <view class="date-header">
            <view v-if="calendarData.yearMonth" class="calendar-tips">【{{ calendarData.yearMonth }}】</view>
            <view :class="calendarData.yearMonth ? 'can-click' : ''" @click="changeCalendar">{{ calendarData.dateHeader }}</view>
          </view>
          <view class="lunar-header">{{ calendarData.dateLunarHeader }}</view>
        </view>
        <view class="arrow" @click="changeCalendar('next')">
          <image src="/static/icons/rarrow.png" mode="aspectFit" />
        </view>
      </view>
      
      <view class="calendar-row">
          <view class="week-item row-item" v-for="(item, index) in calendarData.weekNames" :key="index">
            {{ item }}
          </view>
          <view
            v-for="(item, index) in calendarData.dateList" :key="index"
            class="row-item date-item"
            :class="item.isToday ? item.todayClass : index == calendarData.activeIndex ? 'active-item': ''" 
            @click="clickDateItem(item, index)"
          >
            <view :class="item.isExclude ? 'text ex-text' : item.weekIndex >= 5 ? 'weekly text': 'text'">{{ item.date }}</view>
            <view
              :class="item.isExclude ? 'extra-text ex-text' : item.weekIndex >= 5 ? 'weekly extra-text': 'extra-text'"
              :style="item.style"
            >
              {{ item.umeText || item.lunarMonth }}
            </view>
          </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Solar } from "@/utils/mlunar.js";
  import { dateFormat, generateMonthDates } from '@/utils/index'
  import TnDateTimePicker from '@/uni_modules/tuniaoui-vue3/components/date-time-picker/src/date-time-picker.vue'
  
  const skipDatePickerShow = ref(false)
  const skipToDate = ref('')
  
  const calendarData = reactive({
    activeIndex: -1,
    dateHeader: '',
    dateLunarHeader: '',
    flagDate: new Date(), // 标记日
    isNotCurrent: false,
    yearMonth: '',
    weekNames: ['一', '二', '三', '四', '五', '六', '日'],
    dateList: [],
  })
  
  // 父组件用API
  defineExpose({
    getFlagDate: () => {
      
      if (calendarData.activeIndex < 0) {
        // const curDate = new Date();
        const curDate = calendarData.flagDate
        // return calendarData.flagDate
        return {year: curDate.getFullYear(), month: curDate.getMonth(), date: curDate.getDate()}
      } else {
        const {year, month, date} = calendarData.dateList[calendarData.activeIndex]
        return {year, month, date}
      }
    },
    
    setUmeDateText: (data) => {
      // data是dict
      // console.log('设置日历的文字:', data)
      for (let k in data) {
        for (let i=0; i < calendarData.dateList.length; i++) {
          let dt = calendarData.dateList[i]
          let _ymd = `${dt.year}${dt.month}${dt.date}`
          if (k == _ymd) {
            // console.log(k, dt);
            dt.umeText = data[k][0]
            dt.style = data[k][1]
            break;
          }
        }
      } 
      // console.log(calendarData.dateList);
    }
  })
  
  onMounted(() => {
    // 生成本月数据
    setCalendar();
  })
  
  // 方法
  
  // 确定选择日期
  const confirmSkipToDate = (value) => {
    // console.log(value);
    calendarData.flagDate = new Date(value);
    calendarData.activeIndex = -1;
    setCalendar();
    emitMonthChange()
  }
  
  const closeSkipDatePicker = () => {
    skipDatePickerShow.value = false
  }
  
  // 获取农历
  const getLunarText = (item) => {
    const solar = Solar.fromDate(new Date(item.year, item.month, item.date));
    let lunarMonth = solar.getLunar().getDayInChinese();
    if (lunarMonth == '初一') {
      lunarMonth = solar.getLunar().getMonthInChinese() + '月';
    }
    return lunarMonth
  }
  
  // 设置头部日期
  const setCalendarHeader = (dateItem) => {
    dateItem = dateItem || new Date()
    const solar = Solar.fromDate(dateItem);
    const lunar = solar.getLunar();
    const monthStr = (solar.getMonth() + '').padStart(2, '0');
    const dayStr = (solar.getDay() + '').padStart(2, '0');
    calendarData.dateHeader = `${solar.getYear()}年${monthStr}月${dayStr}日`;
    
    let dateLunarHeaer = lunar.getYearInGanZhi() + '年';
    dateLunarHeaer += lunar.getMonthInGanZhi() + '月';
    dateLunarHeaer += lunar.getDayInGanZhi() + '日';
    dateLunarHeaer += '【' + lunar.getMonthInChinese() + '月' + lunar.getDayInChinese() + '】';
    calendarData.dateLunarHeader = dateLunarHeaer;
  }
  
  // 设置月份日期
  const setCalendar = () => {
    const curDateObj = new Date();
    const curYear = curDateObj.getFullYear();
    const curMonth = curDateObj.getMonth();
    const curDate = curDateObj.getDate();
    
    const flagYear = calendarData.flagDate.getFullYear();
    const flagMonth = calendarData.flagDate.getMonth();
    let weekIndex = calendarData.flagDate.getDay() - 1;
    if (weekIndex == -1) weekIndex = 6;
    
    // 设置yearMonth提示
    if (curYear == flagYear && curMonth == flagMonth) {
      calendarData.yearMonth = ''
      calendarData.isNotCurrent = false;
    } else {
      calendarData.yearMonth = flagYear + '年' + (flagMonth + 1) + '月'
      calendarData.isNotCurrent = true;
    }
    const dates = generateMonthDates(flagYear, flagMonth)
		// console.log(dates);
    let dateList = dates.map(item => {
      item.isToday = curYear == item.year && curMonth == item.month && curDate == item.date;
      if (item.isToday) {
        item.todayClass = 'today-item'
      }
      item.lunarMonth = getLunarText(item);
      return item;
    });
    
    // 处理开始日期
    if (dateList.length > 0) {
      
      // 处理前后日期
      const flagSolar = Solar.fromDate(new Date(flagYear, flagMonth, 1));
      const preMonth = flagSolar.nextMonth(-1);
      const nextMonth = flagSolar.nextMonth(1);
      
      const firstDate = dateList[0]
      const lastDate = dateList[dateList.length - 1]
      
      if (firstDate.weekIndex > 0) {
        const preDates = generateMonthDates(preMonth.getYear(), preMonth.getMonth() - 1);
        const preList = preDates.slice(preDates.length - firstDate.weekIndex , preDates.length).map(item => {
          item.lunarMonth = getLunarText(item);
          item.isExclude = true;
          return item
        })
        dateList = preList.concat(dateList)
      }
      // 处理结束日期
      if (lastDate.weekIndex < 6) {
        const nextDates = generateMonthDates(nextMonth.getYear(), nextMonth.getMonth() - 1);
        const nextList = nextDates.slice(0, 6 - lastDate.weekIndex).map(item => {
          item.lunarMonth = getLunarText(item);
          item.isExclude = true;
          return item;
        })
        dateList = dateList.concat(nextList);
      }
    }
    calendarData.dateList = dateList;
    // 设置标头
    setCalendarHeader(null);
  }
  
  // 点击日期
  const clickDateItem = (item, index) => {
    if (item.isExclude) return; 
    calendarData.activeIndex = index;
    // 去除isToday的样式
    calendarData.dateList.forEach(d => {
      if (d.isToday && !item.isToday) {
        d.todayClass = 'today-focus'
      }
      if (item.isToday) {
        d.todayClass = 'today-item'
      }
    })
    setCalendarHeader(new Date(item.year, item.month, item.date));
    emitDateClick(item);
  }
  
  // 改变月份,回到今日
  const changeCalendar = (action) => {
    let monthCount = 0;
    if (action === 'prev') {
      monthCount = -1;
    } else if (action === 'next') {
      monthCount = 1
    } else {
      // 回到今天
      const cDate = new Date()
      const cDateStr = dateFormat(cDate, '', true)
      const flagDateStr = dateFormat(calendarData.flagDate, '', true)
      // console.log(cDateStr, flagDateStr);
      if (cDateStr == flagDateStr) {
        // 日期是否是今日，是的话弹窗选择输入跳转的日期
        skipDatePickerShow.value = true
        return
      } else {
        // 否则直接回到今日
        calendarData.flagDate = new Date();
        monthCount = 0
      }
    }
    
    const flagYear = calendarData.flagDate.getFullYear();
    const flagMonth = calendarData.flagDate.getMonth();
    const solar = Solar.fromDate(new Date(flagYear, flagMonth, 1));
    const toMonth = solar.nextMonth(monthCount);
    calendarData.flagDate = new Date(toMonth.getYear(), (toMonth.getMonth() - 1), 1);
    calendarData.activeIndex = -1;
    setCalendar();
    emitMonthChange()
  }
  
  // 事件
  
  const emits = defineEmits(['dateClick', 'monthChange'])
  const emitDateClick = (item) => {
    emits('dateClick', item)
  }
  const emitMonthChange = () => {
    const flagYear = calendarData.flagDate.getFullYear();
    const flagMonth = calendarData.flagDate.getMonth();
    emits('monthChange', {year: flagYear, month: flagMonth})
  }
  
  // API
  const getFlagDate = () => {
    return {year: 2024}
  }
</script>

<style lang="scss">
  .content {
    .calendar-box {
      border-bottom: 1px solid #eee;
      .calendar-header {
        display: flex;
        justify-content: space-around;
        flex-direction: row;
        align-items: center;
        border-bottom: 1px solid #eee;
        margin-bottom: 20rpx;
        padding-bottom: 10rpx;
        .arrow {
          width: 50rpx;
          height: 50rpx;
          background-color: #fff;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 25rpx;
          image {
            width: 100%;
            height: 100%;
            // transform: scale(0.7)
          }
        }
        .date-header,.lunar-header {
          line-height: 50rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: row;
          image {
            width: 50rpx;
            height: 50rpx;
            transform: scale(0.8)
          }
          .can-click{
            color: #eb112c;
            text-decoration-line: underline;
            text-decoration-color: #d33682; /* 红色 */
            text-decoration-style: solid; /* 虚线 */
          }
        }
      }
      .calendar-tips {
        text-align: center;
        font-size: 30rpx;
        color: #d33682;
      }
      .calendar-row {
        display: flex;
        justify-content: flex-start;
        // align-items: center; 
        flex-direction: row;
        flex-wrap: wrap;
        .week-item {
          border-radius: 0;
          // height: 70rpx;
          font-size: 26rpx;
          line-height: 40rpx;
          font-weight: 700;
        }
        .row-item {
          display: flex;
          justify-content: center;
          flex-direction: column;
          text-align: center;
          width: calc(100% / 7);
          margin-bottom: 4rpx;
          .weekly {
            color: #666;
          }
          .ex-text {
            color: #aaa;
          }
        }
        .date-item {
          border-radius: 15%;
          height: 70rpx;
          .extra-text {
            font-size: 20rpx;
          }
        }
        .today-item {
          background-color: #e66669;
          box-shadow: 0 0 12rpx 0rpx #bbb;
          .text,.extra-text {
            color: #fff;
          }
        }
        .today-focus {
          background-color: #fff;
          box-shadow: 0 0 12rpx 0rpx #999;
          .text,.extra-text {
            color: #eb112c;
            font-weight: 700;
          }
        }
        .active-item {
          background-color: #999;
          .text,.extra-text {
            color: #fff;
          }
        }
      }
    }
  }
</style>